# 接口回复
import csv
import os

from config import GlobalConfig
from core.ai_model import dify_ai_reply
from core.getShareUrl import get_share_url
from lib import itchat
from core.logger import Logger
import pandas as pd

logger = Logger("WeChatBot")
def restart_bot(msg,payload,ActualNickName):

    if msg["FromUserName"] != GlobalConfig.USER_INFO['UserName']:
        reply = dify_ai_reply(payload)
        if ActualNickName:
            itchat.send_msg(f"@{ActualNickName} "+reply['answer'], msg['FromUserName'])
        else:
            itchat.send_msg(reply['answer'], msg['FromUserName'])
        logger.info(f"Friend question logs: 【{msg['Type']}】 {msg['Content']}")
        if reply:
            logger.info(f"User reply logs: : {reply['answer']}")

def handle_text_msg(msg,ActualNickName):
    """
    处理文本消息。

    :param msg: 微信消息对象
    """
    payload = {
        "inputs": {},
        "query": msg["Content"],
        "response_mode": "blocking",
        "conversation_id": "",
        "user": msg['FromUserName'],
        "files": []
    }
    restart_bot(msg,payload,ActualNickName)



def handle_map_msg(msg,ActualNickName):
    """
    处理位置消息。

    :param msg: 微信消息对象
    """
    payload = {
        "inputs": {},
        "query": msg["Content"].split("区")[0]+"天气",
        "response_mode": "blocking",
        "conversation_id": "",
        "user": msg['FromUserName'],
        "files": []
    }

    restart_bot(msg,payload,ActualNickName)


def handle_card_msg(msg,ActualNickName):
    """
    处理名片消息。

    :param msg: 微信消息对象
    """
    logger.info(f"Received card message from {msg['FromUserName']}: {msg['Content']}")


def handle_note_msg(msg,ActualNickName):
    """
    处理通知消息。

    :param msg: 微信消息对象
    """
    logger.info(f"Received note message from {msg['FromUserName']}: {msg['Content']}")


def handle_sharing_msg(msg,ActualNickName):
    """
    处理分享消息。

    :param msg: 微信消息对象
    """
    url = get_share_url(msg['Content'])
    if url == None:
        logger.info(f"Received sharing message from {msg['FromUserName']}: 公众号链接为空")
    else:
        payload = {
            "inputs": {},
            "query": f"type:wx web_url:{url}",
            "response_mode": "blocking",
            "conversation_id": "",
            "user": msg['FromUserName'],
            "files": []
        }

        restart_bot(msg, payload,ActualNickName)



def handle_picture_msg(msg,ActualNickName):
    """
    处理图片消息。

    :param msg: 微信消息对象
    """
    logger.info(f"Received picture message from {msg['FromUserName']}: {msg['Content']}")


def handle_recording_msg(msg,ActualNickName):
    """
    处理语音消息。

    :param msg: 微信消息对象
    """
    logger.info(f"Received recording message from {msg['FromUserName']}: {msg['Content']}")


def handle_attachment_msg(msg,ActualNickName):
    """
    处理附件消息。

    :param msg: 微信消息对象
    """
    handle_file_msg(msg)


def handle_video_msg(msg,ActualNickName):
    """
    处理视频消息。

    :param msg: 微信消息对象
    """
    logger.info(f"Received video message from {msg['FromUserName']}: {msg['Content']}")


def handle_file_msg(msg,ActualNickName):
    """
    处理接收到的文件消息（附件、图片、录音、视频）。

    :param msg: 微信消息对象
    """
    try:
        # 记录接收到的消息的来源和类型

        # 指定保存文件的目录
        base_dir = 'received_files'
        file_extension = os.path.splitext(msg['FileName'])[1].lower()
        if file_extension == '.pdf':
            sub_dir = 'pdf'
        elif file_extension in ['.jpg', '.jpeg', '.png', '.gif']:
            sub_dir = 'images'
        elif file_extension in ['.mp3', '.wav', '.aac']:
            sub_dir = 'audio'
        elif file_extension in ['.mp4', '.avi', '.mkv']:
            sub_dir = 'video'
        else:
            sub_dir = 'other'
        save_dir = base_dir+'\\'+sub_dir
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)

        # 将文件消息存入csv表格中



        # 构建完整的文件路径
        file_path = os.path.join(save_dir, msg['FileName'])


        # 下载并保存文件
        msg['Text'](file_path)
        # 保存文件消息
        csv_file = os.path.join(base_dir, 'file_messages.csv')
        file_exists = os.path.isfile(csv_file)
        with open(csv_file, mode='a', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            if not file_exists:
                writer.writerow(['FromUserName', 'FileName', 'FileType', 'SavePath', 'Timestamp'])
            writer.writerow([msg['FromUserName'], msg['FileName'], file_extension, file_path, msg['CreateTime']])
        df = pd.read_csv(csv_file)
        print(df)

        # 可以在这里添加更多的处理逻辑，例如发送确认消息给发送者
        if ActualNickName:
            itchat.send(f"@{ActualNickName} 文件 {msg['FileName']} 已接收并保存。", toUserName=msg['FromUserName'])
        else:
            itchat.send(f"文件 {msg['FileName']} 已接收并保存。", toUserName=msg['FromUserName'])
        logger.info(f"Received file message from {msg['FromUserName']}: {msg['FileName']}")

    except Exception as e:
        # 记录错误信息
        print(f"Error handling file message: {e}")



# 发送文件
def send_file(file_path, to_user_name):
    """
    发送文件到指定用户。

    :param file_path: 文件路径
    :param to_user_name: 目标用户名
    """
    itchat.send_file(file_path, toUserName=to_user_name)